package com.csmk.control;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

@Slf4j
public class MKSClient {

    private OkHttpClient client = new OkHttpClient();

    private String deviceIp;

    public MKSClient(String deviceIp) {
        this.deviceIp = deviceIp.split("%")[0];
    }

    public Callback defaultCallBack = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            log.error("请求失败",e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            log.info("请求成功:{}",response.body().string());
        }
    };

    public void sendTask(Task task) {
        sendTask(task,null);
    }

    public void sendTask(Task task,Callback callback) {
        HttpUrl.Builder baseHttpUrl = new HttpUrl.Builder()
                .scheme("http")
                .host(deviceIp)
                .addPathSegment(task.taskType().url)
                .port(8081);
        Request.Builder requestBuilder = new Request.Builder();
        Request request = null;
        if (task == null || !task.valid()){
            throw new RuntimeException("参数异常");
        }
        // get请求添加queryParam
        if (task.taskType().requestType.equals(RequestType.GET)) {
            if(task.data() != null && task.taskType().paramName != null){
                baseHttpUrl.addQueryParameter(task.taskType().paramName,task.data().toString());
            }
            request = requestBuilder.url(baseHttpUrl.build())
                    .build();
        }

        if(task.taskType().requestType.equals(RequestType.POST)){
            RequestBody body = RequestBody.create(
                    task.data().toString(),
                    MediaType.get("application/json; charset=utf-8")
            );
            request = requestBuilder.url(baseHttpUrl.build())
                    .post(body)
                    .build();
        }
        if (callback == null){
            callback = defaultCallBack;
        }
        client.newCall(request).enqueue(callback);

    }


}
